package com.siyoumi.interceptor;

import com.siyoumi.component.XSpringContext;
import com.siyoumi.entity.SysAccount;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.RedisKey;
import com.siyoumi.service.SysAccountService;
import com.siyoumi.component.XJwt;
import com.siyoumi.component.XRedis;
import com.siyoumi.util.*;
import com.siyoumi.component.http.XHttpContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//后台
@Slf4j
public class AdminInterceptor
        extends InterceptorBase
        implements HandlerInterceptor {
    /**
     * 执行前
     *
     * @return boolean
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("BEGIN");

        if ("OPTIONS".equals(request.getMethod().toUpperCase())) {
            return false;
        }

        XReturn r = authToken();
        if (r.err()) {
            return returnErr(response, r);
        }
        log.debug(XJson.toJSONString(r));

        r.setData("type", "admin");
        String x = r.getData("acc_x_id");
        XHttpContext.setX(x); //设置x
        XHttpContext.set(XHttpContext.keyTokenData, r);


        SysAccountService sysAccountService = XSpringContext.getBean(SysAccountService.class);
        //检查权限
        SysAccount entityAcc = sysAccountService.getSysAccountByToken();
        r = sysAccountService.authCheck(entityAcc);
        if (r.err()) {
            return returnErr(response, r);
        }

        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.debug("END");
    }


    /**
     * 验证token
     *
     * @return 验证结果
     */
    protected XReturn authToken() {
        log.debug("检查token");
        String token = XHttpContext.getToken();
        if (XStr.isNullOrEmpty(token)) {
            return EnumSys.TOKEN_MISS.getR();
        }

        String redisKeyToken = RedisKey.getAdminToken(token);
        XRedis redis = XRedis.getBean();
        if (!redis.exists(redisKeyToken)) {
            return EnumSys.TOKEN_EXISTS.getR();
        }
        String jwtToken = redis.get(redisKeyToken);

        XJwt jwt = XJwt.getBean();
        XReturn r = jwt.parseToken(jwtToken);
        if (r.err()) {
            return EnumSys.TOKEN_ERR.getR();
        }

        return r;
    }
}
